package com.minyifang.wcspf.work.ui.user.activities;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.minyifang.wcspf.R;
import com.minyifang.wcspf.common.base.BaseMvpActivity;
import com.minyifang.wcspf.common.utils.BitmapHelper;
import com.minyifang.wcspf.common.utils.ImageUtils;
import com.minyifang.wcspf.common.utils.LogUtil;
import com.minyifang.wcspf.common.utils.RxGalleryMyApi;
import com.minyifang.wcspf.common.utils.SimpleRxGalleryFinal;
import com.minyifang.wcspf.common.utils.ToastHelper;
import com.minyifang.wcspf.common.utils.ToastUtils;
import com.minyifang.wcspf.common.widgets.RoundImageView;
import com.minyifang.wcspf.work.model.HttpRespond;
import com.minyifang.wcspf.work.ui.home.model.UserInfoBean;
import com.minyifang.wcspf.work.ui.user.model.UploadPicBean;
import com.minyifang.wcspf.work.ui.user.presenter.MemberInfoPresenter;
import com.minyifang.wcspf.work.ui.user.view.MemberInfoView;
import com.yalantis.ucrop.util.FileUtils;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.rxgalleryfinal.rxbus.RxBusResultDisposable;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageRadioResultEvent;
import cn.finalteam.rxgalleryfinal.ui.base.IRadioImageCheckedListener;

/**
 * 基本信息
 */
public class MemberInfoActivity extends BaseMvpActivity<MemberInfoView, MemberInfoPresenter> implements MemberInfoView, View.OnClickListener {

    float mDensity;
    private BottomSheetDialog mBottomSheetDialog;

    @BindView(R.id.tv_user_name)
    TextView mTvUserName;
    /*@BindView(R.id.et_nickname)
    EditText mEtNickName;*/
    @BindView(R.id.et_real_name)
    EditText mEtRealName;

    @BindView(R.id.tv_birthday)
    TextView mTvBirthday;
    @BindView(R.id.tv_gender)
    TextView mTvGender;
    @BindView(R.id.tv_mobile)
    TextView mTvMobile;

    @BindView(R.id.iv_head_img)
    RoundImageView mIvAvatar;

    private String mUploadImgUrl;
    private UserInfoBean mUserInfo;

    private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_member_info;
    }

    @Override
    protected void initView() {
        mDensity = getResources().getDisplayMetrics().density;
        genDialog();
        mEtRealName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mUserInfo != null) {
                    mUserInfo.setRealname(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        /*mEtNickName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mUserInfo != null) {
                    mUserInfo.setNickname(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });*/
    }

    @OnClick(R.id.fl_change_avatar)
    void fl_change_avatar() {
        if (mBottomSheetDialog != null)
            mBottomSheetDialog.show();
    }

    @OnClick(R.id.fl_choose_gender)
    void fl_choose_gender() {
        new AlertDialog.Builder(this).setItems(new String[]{"男", "女"}, (dialog, which) -> {
            if (mUserInfo != null) {
                int gender = Math.abs(1 - which);
                mUserInfo.setSex(gender);
                mTvGender.setText(gender == 1 ? "男" : "女");
            }
        }).show();
    }

    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
        mPresenter.userInformation();
    }

    @Override
    protected MemberInfoPresenter createPresenter() {
        return new MemberInfoPresenter();
    }

    @Override
    public void forgetPwdRes(HttpRespond respond) {

    }

    @OnClick(R.id.btn_save)
    void btn_save() {
        if (mUserInfo != null) {
            mPresenter.updateUserInformation(mUploadImgUrl, mUserInfo);
        }
    }

    @OnClick(R.id.fl_choose_birthday_date)
    void fl_choose_birthday_date() {
        new TimePickerBuilder(this, (date, v) -> {
            String d = mSimpleDateFormat.format(date);
            mTvBirthday.setText(d);
            mUserInfo.setBirthday(d);
        }).build().show();
    }

    @Override
    public void onRequestFailed(String message) {
        ToastHelper.getInstance(this).showWarn(message);
    }

    @Override
    public void onGetUserInfo(UserInfoBean userInfoBean) {
        mUserInfo = userInfoBean;
        mTvUserName.setText(userInfoBean.getUsername());
        mTvGender.setText(userInfoBean.getSex() == 1 ? "男" : "女");
        //mEtNickName.setText(userInfoBean.getNickname());
        mEtRealName.setText(userInfoBean.getRealname());
        mTvBirthday.setText(TextUtils.isEmpty(userInfoBean.getBirthday()) ? "尚未设置" : userInfoBean.getBirthday());
        mTvMobile.setText(userInfoBean.getMobile());
        ImageUtils.getInstance().showImage(userInfoBean.getHead(), mIvAvatar);
    }

    @Override
    public void onUploadPicSucceed(List<UploadPicBean> data) {
        mUploadImgUrl = data.get(0).savePath;
        ImageUtils.getInstance().showImage(data.get(0).viewPath, mIvAvatar);
    }

    @Override
    public void onUpdateUserInfoSucceed(String message) {
        ToastHelper.getInstance(this).showSucceed(message);
        finish();
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        hideLoadingView();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case 0x996:
                mBottomSheetDialog.dismiss();
                AndPermission.with(MemberInfoActivity.this).permission(Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE).onGranted(permissions -> chooseFromAlbum()).start();
                break;
            case 0x837:
                mBottomSheetDialog.dismiss();
                AndPermission.with(MemberInfoActivity.this).permission(Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE).onGranted(permissions -> takePhoto()).start();
                break;
        }
    }

    private void genDialog() {
        LinearLayout linearLayout = new LinearLayout(this);
        mBottomSheetDialog = new BottomSheetDialog(this);
        mBottomSheetDialog.setContentView(linearLayout);
        ViewGroup.LayoutParams layoutParams = linearLayout.getLayoutParams();
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        linearLayout.setLayoutParams(layoutParams);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        genTextView(linearLayout, "从相册中选择", ContextCompat.getColor(this, R.color.colorTextContent), 0x996);
        LinearLayout.LayoutParams params3 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1);
        View child1 = new View(this);
        child1.setBackgroundResource(R.color.colorSplitLine);
        linearLayout.addView(child1, params3);
        genTextView(linearLayout, "相机", ContextCompat.getColor(this, R.color.colorTextContent), 0x837);
    }

    private void genTextView(LinearLayout linearLayout, String text, int color, int id) {
        TextView textView = new TextView(this);
        textView.setTextSize(16);
        textView.setTextColor(color);
        textView.setId(id);
        textView.setGravity(Gravity.CENTER);
        textView.setPadding(((int) (10 * mDensity)), ((int) (14 * mDensity)), ((int) (10 * mDensity)), ((int) (14 * mDensity)));
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        linearLayout.addView(textView, layoutParams);
        textView.setText(text);
        textView.setOnClickListener(this);
    }

    private void chooseFromAlbum() {
        RxGalleryMyApi instance =
                RxGalleryMyApi.getInstance(this);
        instance.openGalleryRadioImgDefault(new RxBusResultDisposable<ImageRadioResultEvent>() {
            @Override
            protected void onEvent(ImageRadioResultEvent imageRadioResultEvent) throws Exception {
                LogUtil.i("只要选择图片就会触发");
            }
        }).onCropImageResult(
                new IRadioImageCheckedListener() {
                    @Override
                    public void cropAfter(Object t) {
                        File file = (File) t;
//                        RequestOptions options = new RequestOptions();
//                        options.centerCrop();
                        compressAndUploadHeadImg(file.getAbsolutePath());
                        LogUtil.i("裁剪完成");
                    }

                    @Override
                    public boolean isActivityFinish() {
                        LogUtil.i("返回false不关闭，返回true则为关闭");
                        return true;
                    }
                });
    }

    private void takePhoto() {
        SimpleRxGalleryFinal.get().init(
                new SimpleRxGalleryFinal.RxGalleryFinalCropListener() {
                    @NonNull
                    @Override
                    public Activity getSimpleActivity() {
                        return MemberInfoActivity.this;
                    }

                    @Override
                    public void onCropCancel() {
                        ToastUtils.showShort(getSimpleActivity(), "操作被取消");
                    }

                    @Override
                    public void onCropSuccess(@Nullable Uri uri) {
                        if (uri != null) {
                            String path = FileUtils.getPath(getSimpleActivity(), uri);
                            compressAndUploadHeadImg(path);
                        } else {
                            ToastUtils.showShort(getSimpleActivity(), "图片不存在");
                        }
                    }

                    @Override
                    public void onCropError(@NonNull String errorMessage) {
                        ToastUtils.showShort(getSimpleActivity(), errorMessage);
                    }
                }
        ).openCamera();
    }

    private void compressAndUploadHeadImg(String path) {
        File file = new File(path);
        // 压缩头像并保存
        Bitmap bitmap = BitmapHelper
                .compressImage(BitmapFactory.decodeFile(file.getAbsolutePath()));
        LogUtil.e(file.getParent());
        File PHOTO_DIR = new File(file.getParent());
        File headFile = new File(PHOTO_DIR, "head.jpg");//设置文件名称
        if (headFile.exists()) {
            headFile.delete();
        }
        try {
            headFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(headFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 上传用户头像
        mPresenter.updateImg(headFile);
        LogUtil.e(headFile.getAbsolutePath());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        SimpleRxGalleryFinal.get().onActivityResult(requestCode, resultCode, data);
    }
}
